<template>
  <div class="component-video-box elx-imgbox">
    <el-dialog
      v-model="visible"
      :title="$t('videoManager.picManager')"
      class="component-video-box elx-imgbox-dialog"
      top="40px"
      width="900px"
      :append-to-body="visible"
      @close="onHandleDialogClose"
    >
      <div
        class="demo-tabs"
      >
        <div
          v-if="options.activeTab==='pick'"
          class="pick-block"
        >
          <div
            v-if="isLoading"
            class="elx-img-list-loading"
          >
            <el-icon><Loading /></el-icon>
          </div>
          <!-- native modifier has been removed, please confirm whether the function has been affected  -->
          <el-form
            :inline="true"
            :model="dataForm"
            class="demo-form-inline form"

            @submit.prevent
          >
            <el-form-item>
              <el-input
                v-model="fileName"
                size="default"
                :placeholder="$t('videoManager.videoName')"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <div
                class="primary-btn default-btn"
                @click="onSearchImg"
              >
                {{ $t("videoManager.query") }}
              </div>
              <div
                v-if="options.enableUpload"
                class="default-btn primary-btn"
                plain
                style="margin-left:10px"
                @click="onUploadFileBtn"
              >
                {{ $t("videoManager.uploadVideo") }}
              </div>
            </el-form-item>
            <!-- <el-form-item>
              <el-button type="primary" @click="clean">清空</el-button>
            </el-form-item>-->
          </el-form>
          <div class="box">
            <div class="group group-box">
              <div
                :class="['group-item',groupId === 0 ?'active': '']"
                @click="onClickGroup(0)"
              >
                <span class="group-name">{{ $t("videoManager.AllVideos") }}</span>
              </div>
              <div
                v-for="(item) in groupList"
                :key="item.attachFileGroupId"
                :class="['group-item',groupId === item.attachFileGroupId ?'active': '']"
              >
                <span
                  class="group-name"
                  @click="onClickGroup(item.attachFileGroupId)"
                >{{ item.name }}</span>
              </div>
            </div>
            <div class="img-list">
              <div class="elx-main elx-img-list">
                <div
                  v-for="(img, itemIndex) in imgRes.records"
                  :key="itemIndex"
                  class="img-item"
                >
                  <div
                    class="thumb-wp"
                  >
                    <video
                      :src="checkFileUrl(img.filePath)"
                      class="showVideo"
                      style="width:175px;height:110px;"
                    />
                  </div>
                  <div
                    class="title"
                  >
                    {{ img.fileName }}
                  </div>
                  <!-- <div class="label" v-if="img.label">{{img.label}}</div> -->
                  <span
                    v-if="img.selected"
                    class="selected"
                  >
                    <el-icon class="icon"><Check /></el-icon>
                  </span>
                  <!-- 蒙版 -->
                  <div class="modal">
                    <el-icon
                      size="30"
                      class="icon"
                      @click="onPreviewVedio(img, itemIndex)"
                    >
                      <View />
                    </el-icon>
                    <el-icon
                      size="30"
                      class="icon"
                      @click="onClickListImage(img)"
                    >
                      <CircleCheck />
                    </el-icon>
                  </div>
                </div>
                <div
                  v-show="!(imgRes.records&&imgRes.records.length)"
                  class="noData"
                >
                  {{ $t("order.noData") }}
                </div>
              </div>
              <el-pagination
                layout="total, prev, pager, next"
                :current-page="imgRes.current"
                :page-size="imgRes.size"
                :total="imgRes.total"
                @current-change="onPageNumChange"
              />
            </div>
          </div>
          <div class="elx-foot">
            <el-badge
              v-if="!type"
              :value="images.length"
              class="item"
            >
              <div
                class="default-btn"
                @click="visible = false"
              >
                {{ $t("resource.cancel") }}
              </div>
              <div
                :class="[images.length == 0?'disabled-btn':'','default-btn primary-btn']"
                :disabled="images.length == 0"
                style="margin-right:3px;"
                @click="onConfirm"
              >
                {{ $t("resource.confirm") }}
              </div>
            </el-badge>
            <div
              v-else
              :class="[images.length == 0?'disabled-btn':'','default-btn primary-btn']"
              :disabled="disabled"
              @click="onConfirm"
            >
              {{ $t("resource.confirm") }}
            </div>
          </div>
        </div>

        <div
          v-if="options.activeTab==='upload' && options.enableUpload"
          class="upload-block"
        >
          <div class="elx-upload-main">
            <div class="upload-title">
              {{ $t("resource.selectGroup") }}:
            </div>
            <div class="select-group-box">
              <div class="select-group-box-item">
                {{ $t("resource.group") }}:
              </div>
              <el-select
                v-model="selectGroup"

                clearable
                :placeholder="$t('resource.selectGroup')"
                class="select-group-box-item"
              >
                <el-option
                  v-for="item in groupList"
                  :key="item.attachFileGroupId"
                  :label="item.name"
                  :value="item.attachFileGroupId"
                />
              </el-select>
              <el-button
                style="margin-left: 10px"
                type="primary"
                link
                @click="onCreateGroup()"
              >
                {{ $t('resource.newGroup') }}
              </el-button>
            </div>
            <div class="upload-title">
              {{ $t("videoManager.selectLocalVideo") }}
            </div>
            <!-- 视频预览 -->
            <div class="upload-video-box">
              <div
                v-for="(item, index) in videoList"
                :key="index"
                class="video-preview"
              >
                <video
                  v-if="item.url"
                  class="upShowVideo"
                  :src="checkFileUrl(item.url)"
                  controls="controls"
                  style="width:175px;height:88px;"
                />
                <!-- 显示查看和删除的按钮弹窗 -->
                <div
                  class="avatar-uploader-popup"
                >
                  <el-icon @click="preDeleteVideo(index)">
                    <Delete />
                  </el-icon>
                </div>
                <!-- 显示上传进度 -->
                <div
                  v-show="isSubmit"
                  class="progress"
                >
                  <el-progress
                    type="circle"
                    :width="80"
                    :color="colors"
                    :percentage="item.progress || 0"
                  />
                </div>
              </div>
            </div>
            <el-upload
              v-show="!uploadHide"
              ref="uploadRef"
              class="upload-img-preview"
              list-type="picture-card"
              action=""
              :multiple="true"
              accept="video/*"
              :auto-upload="false"
              :show-file-list="false"
              :limit="options.limit"
              :before-upload="beforeUploadVideo"
              :http-request="httpRequest"
              :on-change="onUploadChange"
              :on-exceed="onUploadExceedTip"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <div
              v-show="uploadHide"
              style="height:20px;"
            />

            <div class="upload-tip">
              {{ uploadTips() }}
            </div>

            <div class="elx-upload-foot">
              <div
                class="default-btn"
                @click="options.activeTab = 'pick'"
              >
                {{ $t("shop.return") }}
              </div>
              <div
                class="primary-btn default-btn"
                @click="onUploadConfirm"
              >
                {{ $t("videoManager.confirmUpload") }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <group-add-or-update
      v-if="groupVisible"
      ref="groupAddOrUpdateRef"
      @get-group-data="getGroupList"
    />
  </div>
</template>

<script type="text/babel" setup>
import { ElMessage } from 'element-plus'
import http, { uploadFile } from '@/utils/http.js'

const emit = defineEmits(['refreshPic'])

const images = ref([]) // 已选视频
let fileIds = [] // 已选视频的fileId
const dataForm = reactive({})
const uploadHide = ref(false)
let uploadFileNum = 0
const groupVisible = ref(false)
const options = reactive({
  multiple: true, // 是否支持选取多个视频
  limit: 10, // 最多可选择视频数量
  maxSize: 2, // 最大尺寸（M）
  activeTab: 'pick',
  enableUpload: true, // 是否启用视频上传
  callback: null
})
const colors = [
  { color: '#f56c6c', percentage: 20 },
  { color: '#e6a23c', percentage: 40 },
  { color: '#5cb87a', percentage: 60 },
  { color: '#1989fa', percentage: 80 },
  { color: '#6f7ad3', percentage: 100 }
]
const groupList = ref([]) // 分组列表
const selectGroup = ref('')

const type = ref(2)
const fileName = ref('')
const isLoading = ref(true)
const visible = ref(false)
const disabled = ref(false)

const imgRes = ref({
  current: 1
})
const videoList = ref([])
const groupId = ref(0) // 点击分组
onMounted(() => {
  getGroupList()
  loadListImage()
})

/**
 * 初始化
 * type 1：单  2：多
 */
const uploadRef = ref(null)

// eslint-disable-next-line no-unused-vars
const init = (_type, _limit) => {
  visible.value = true
  isLoading.value = false
  images.value = []
  fileIds = []
  type.value = _type
  if (_type === 1) {
    type.value = true
    disabled.value = true
  } else {
    type.value = false
  }
  if (uploadRef.value) {
    uploadRef.value.uploadFiles = []
  }
  // 获取产品数据 - 第一页的数据
  loadListImage(1)
  getGroupList()
}
defineExpose({ init })
const onConfirm = () => {
  if (type.value) {
    emit('refreshPic', images.value[0].filePath)
  } else {
    const imgPaths = images.value.map(file => {
      return file.filePath
    }).join(',')
    emit('refreshPic', imgPaths)
  }
  visible.value = false
}

/**
 * 点击视频时选中或取消选中视频
 * @param img object
 */
const onClickListImage = (img) => {
  // if(!uploadNumberLimit()) {
  //   return onUploadExceedTip()
  // }
  // 单选图片
  if (type.value) {
    clearListSelected()
    images.value = []
    fileIds = []
    disabled.value = false
  } else {
    // 多选图片-如果已选中则取消选中
    const imgIndex = selectedImageIndex(img)
    if (imgIndex >= 0) {
      // 取消图片已选状态
      img.selected = false
      images.value.splice(imgIndex, 1)
      fileIds.splice(imgIndex, 1)
      return
    }
  }
  if (type.value && !uploadNumberLimit()) {
    message($t('pictureManager.superiorLimit'))
    return false
  }
  images.value.push(JSON.parse(JSON.stringify(img)))
  fileIds.push(img.fileId)
  img.selected = true
}
/**
 * 清除所有已点击视频样式
 */
const clearListSelected = () => {
  if (type.value) {
    const list = imgRes.value.records
    list.forEach(element => {
      element.selected = false
    })
  }
}
/**
     * 按视频名称搜索视频
     */
const onSearchImg = () => {
  loadListImage(1)
}
/**
 * 加载视频列表数据
 * @param page
 */
const loadListImage = (current) => {
  isLoading.value = true
  http({
    url: http.adornUrl('/admin/file/attachFilePage'),
    method: 'get',
    params: http.adornParams({
      current,
      size: 9,
      fileName: fileName.value || null,
      attachFileGroupId: groupId.value,
      type: 2
    })
  }).then(({ data }) => {
    data.records.forEach(img => {
      img.selected = false
    })
    imgRes.value = data
    isLoading.value = false
  })
}

/**
 * 视频已选则返回下标，未选则返回-1
 */
const selectedImageIndex = (img) => {
  for (let i = 0; i < images.value.length; i++) {
    const selectedImg = images.value[i]
    if (selectedImg.fileId === img.fileId) {
      return i
    }
  }
  return -1
}

/**
 * 分页页面变化时刷新数据
 * @param page
 */
const onPageNumChange = (page) => {
  loadListImage(page)
}
/**
 * 获取分组列表
 */
const getGroupList = (data) => {
  groupVisible.value = false
  http({
    url: http.adornUrl('/admin/fileGroup/list'),
    method: 'get',
    params: {
      type: 2 // 1、视频 2、视频 3、文件
    }
  }).then(res => {
    groupList.value = res.data
    // 新建分组 默认选中
    if (data) {
      const newItem = res.data.find(d => d.name == data.name)
      selectGroup.value = newItem.attachFileGroupId
      onClickGroup(newItem.attachFileGroupId)
    }
  })
}
/**
 * 点击分组
 */
const onClickGroup = (id) => {
  groupId.value = id
  loadListImage(1)
}
/**
 * 提交上传
 */
let isSubmit = false
let isConfirm = false
const onUploadConfirm = () => {
  // if (!videoList.length) {
  //   message($t('videoManager.tips1'), false)
  //   return
  // }
  if (isConfirm) {
    return
  }
  isConfirm = true
  isSubmit = true
  fileIds = []
  uploadRef.value?.submit()
}

// eslint-disable-next-line no-unused-vars
const onUploadProgress = (event, file, fileList) => {

}
// 新建分组
const groupAddOrUpdateRef = ref(null)
const onCreateGroup = () => {
  groupVisible.value = true
  nextTick(() => {
    groupAddOrUpdateRef.value?.show(2)
  })
}
/**
 * 点击上传视频按钮
 */
const onUploadFileBtn = () => {
  options.activeTab = 'upload'
  videoList.value = []
  images.value = []
  fileIds = []
  if (uploadRef.value) {
    uploadRef.value.uploadFiles = []
  }
}
/**
 * 上传视频
 */
const httpRequest = (event) => {
  videoList.value.forEach(item => {
    if (item.uid === event.file.uid) {
      uploadFileVideo(event)
    }
  })
}
let resData = []
const uploadFileVideo = (event) => {
  const file = event.file
  http({
    url: http.adornUrl('/admin/file/getPreSignUrl'),
    method: 'get',
    params: http.adornParams({
      fileName: file.name,
      isImFile: false
    })
  }).then(async ({ data }) => {
    await uploadFile(data.preSignUrl, event.file, (evt) => {
      progressFn(event.file, evt)
    }).then(() => {
      resData.push({ fileId: data.fileId, attachFileGroupId: selectGroup.value, fileSize: file.size, type: 2 })
    })
    if (resData.length === uploadFileNum) {
      http({
        url: http.adornUrl('/admin/file/uploadSuccess'),
        method: 'put',
        data: resData
      }).then(() => {
        resData = []
        images.value = []
        fileIds = []
        event.onSuccess(data.fileId)
        disabled.value = true
        uploadRef.value.uploadFiles = []
        options.activeTab = 'pick'
        setTimeout(() => {
          isSubmit = false
          videoList.value = []
        })
        isConfirm = false
        loadListImage(1)
      }).catch((err) => {
        message($t('videoManager.requestError'), true)
        throw err
      })
    }
  })
}
const progressFn = (file, evt) => {
  videoList.value.forEach(d => {
    if (d.uid === file.uid) {
      d.progress = parseInt(evt.loaded / evt.total * 100)
    }
  })
}
// 视频预上传
// eslint-disable-next-line no-unused-vars
const onUploadChange = (file, fileList) => {
  const isLtSize = file.size / 1024 / 1024 < 200
  if (!isLtSize) {
    ElMessage.error($t('videoManager.tips3'))
    return
  }
  if (['video/mp4', 'video/ogg', 'video/webm'].indexOf(file.raw.type) === -1) {
    ElMessage.error($t('videoManager.tips2'))
    return false
  }
  if (isSubmit) {
    return
  }
  const showVideoList = document.getElementsByClassName('upShowVideo') || []
  const videoSrc = URL.createObjectURL(file.raw)
  videoList.value.push({ url: videoSrc, uid: file.uid })
  Array.prototype.forEach.call(showVideoList, (item) => {
    if (!item.paused) {
      item.pause()
    }
  })
  // showVideoList.forEach((item) => {
  //   if (!item.paused) {
  //     item.pause()
  //   }
  // })
}
// 删除预览视频
const preDeleteVideo = (index) => {
  uploadRef.value?.uploadFiles.splice(index, 1)
  videoList.value.splice(index, 1)
}
/**
 * 上传视频前检查合法性
 * @param file
 * @returns {boolean}
 */
const beforeUploadVideo = async (file) => {
  return file.size / 1024 / 1024 < 200
}

const uploadNumberLimit = () => {
  if (!options.multiple) {
    return 1
  }
  return options.limit - images.value.length - uploadFileNum
}

const uploadTypeTip = () => {
  return $t('videoManager.onlySupported') + ' mp4/mov/webm ' + $t('videoManager.video')
}

const uploadSizeTip = () => {
  return $t('videoManager.notExceed') + '20M'
}

const uploadTips = () => {
  const tips = [uploadTypeTip(), uploadSizeTip()]

  if (!options.multiple) {
    return tips.join('，')
  }

  if (images.value.length > 0) {
    tips.push($t('videoManager.alreadyExist') + images.value.length + $t('videoManager.unit'))
  }

  const _uploadFileNum = videoList.value.length
  if (_uploadFileNum > 0) {
    tips.push($t('videoManager.soonUpload') + _uploadFileNum + $t('videoManager.unit'))
  }
  if (_uploadFileNum >= options.limit) {
    uploadHide.value = true
  } else {
    uploadHide.value = false
  }
  uploadFileNum = _uploadFileNum
  tips.push($t('videoManager.remainder') + (options.limit - images.value.length - uploadFileNum) + $t('videoManager.unit') + $t('videoManager.upload'))

  return tips.join(',')
}

/**
 * 选择上传文件超过限制文件个数提示
 */
const onUploadExceedTip = () => {
  message($t('videoManager.maxSelect') + uploadNumberLimit() + $t('videoManager.unit') + $t('videoManager.upload'))
}
const message = (msg, isInfo) => {
  let type = 'error'
  if (isInfo) {
    type = 'info'
  }
  ElMessage({
    message: msg,
    type,
    duration: 1500
  })
}

/**
 * 关闭回调
 */
const onHandleDialogClose = () => {
  fileName.value = ''
}

const onPreviewVedio = (vedio, index) => {
  const video = document.getElementsByClassName('showVideo')[index]
  if (video.requestFullscreen) {
    video.requestFullscreen()
  } else if (video.mozRequestFullScreen) {
    video.mozRequestFullScreen()
  } else if (video.webkitRequestFullscreen) {
    video.webkitRequestFullscreen()
  } else if (video.msRequestFullscreen) {
    video.msRequestFullscreen()
  }
  video.play()
}

</script>

<style lang="scss" scoped>
.component-video-box{
  &.elx-imgbox-dialog {
    $bg: #f6f6f6;
    height: 100% !important;
    :deep(.el-badge) {
      vertical-align: bottom;
    }

    :deep(.el-dialog) {
      width: 820px;
      .el-dialog__header {
        border-bottom: 1px solid #e8e8e8;
      }

      .el-dialog__body {
        padding: 0;
        background: $bg;
      }
    }

    // eslint-disable-next-line vue-scoped-css/no-unused-selector
    .el-tabs {
      :deep(.el-tabs__header) {
        margin-right: 0;
        margin-top: 5px;
        .el-tabs__nav-wrap::after {
          background: $bg;
        }
      }
      :deep(.el-tabs__item.is-active) {
        background: #fff;
      }
      :deep(.el-tabs--left .el-tabs__nav-wrap) {
        padding-top: 15px;
      }

      :deep(.el-tabs__content) {
        min-height: 740px;
        // 弹窗高度
        background: #fff;
      }
    }

    .elx-foot {
      padding: 15px 0 0 10px;
      text-align: right;
      margin-right: 30px;
      :deep(.el-button) {
        margin: 0 0 0 10px;
      }
    }
   .upload-block {
      :deep(.upload-img-preview) {
        padding: 20px;

        /* 上传视频预览改为使用背景视频按比例缩放方式 */
        .el-upload--picture-card,
        .el-upload-list--picture-card .el-upload-list__item,
        .el-upload-list--picture-card .el-upload-list__item .wp {
          width: 90px;
          height: 90px;
          line-height: 98px;
          background-size: cover;
          background-position: 50% 50%;
        }

        .el-upload-list--picture-card .el-upload-list__item-status-label i {
          margin-top: 12px;
          vertical-align: top;
        }
      }

      :deep(.upload-tip) {
        padding: 0 20px;
        font-size: 13px;
        color: #999;
      }

      :deep(.upload-title) {
        font-size: 16px;
        color: #666;
        padding: 20px 0 0 20px;
      }
    }
  }

  .form {
    padding: 15px 0px 0px 20px;
  }

  :deep(.el-upload-list__item-actions) {
    a {
      i {
        color: #fff;
      }
    }
  }
  .upload-video-box {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    .video-preview {
      width: 175px;
      height: 106px;
      display: block;
      text-align: center;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      margin-right: 8px;
      margin-bottom: 5px;
      margin-top: 20px;
      position: relative;

      .progress{
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 106px;
        padding: 13px;
        background: rgba(0, 0, 0, .7);

        :deep(.el-progress__text){
          color: #fff;
        }
      }
    }
    .avatar-uploader-popup{
      width: 100%;
      background: #f6f6f6;
      height: 18px;
    }
  }
  .group-box {
    height: 600px;
    min-width: 200px;
    overflow-x:hidden;
    overflow-y: auto;
  }
  .select-group-box {
    padding: 20px 0 0 20px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .select-group-box-item {
      margin-right: 10px;
    }
  }
  .box {
    display: flex;
    justify-content: flex-start;
    .group {
      min-width: 200px;
      padding: 10px;
      .group-item {
        height: 38px;
        line-height: 38px;
        padding: 0 10px;
        display: flex;
        justify-content: space-between;
        cursor:pointer;

        .group-name {
          width: 180px;
        }
      }
      .group-item:hover{
        background: #F7F7F7;
      }
      .active {
        background: #F7F7F7;
      }
    }
    .img-list {
      // width: 1100px;
      height: 600px;
    }
  }
  .pick-block {
    position: relative;
    $bg: #f6f6f6;
    .elx-img-list-loading {
      position: absolute;
      top: 60px;
      z-index: 9;
      left: 0;
      right: 0;
      width: 100%;
      height: 520px;
      // 加载层高度
      background: #fff;
      text-align: center;

      :deep(.el-icon-loading) {
        font-size: 50px;
        color: #409eff;
        line-height: 460px;
      }
    }

    .elx-img-list {
      padding: 10px;
      min-height: 530px;
      // 视频列表高度
      .noData{
          text-align: center;
          width: 100%;
          margin-top:30% ;
          color: #999;
        }

      .img-item {
        $imgSize: 175px;
        $size: 179px;
        float: left;
        margin: 10px;
        margin-bottom: 20px;
        margin-right: 20px;
        width: $imgSize;
        cursor: pointer;
        position: relative;
        font-size: 12px;

        .title {
          line-height: 24px;
          height: 24px;
          display: block;
          overflow: hidden;
          background: $bg;
          padding: 0 5px;
        }

        .selected {
          position: absolute;
          right: -3px;
          top: -3px;
          width: $size;
          height: 143px;
          border: 3px solid #155bd4;
          border-radius: 3px;
          text-align: right;
          .icon {
            background: #155bd4;
            text-align: center;
            height: 24px;
            width: 24px;
            line-height: 24px;
            display: inline-block;
            font-size: 16px;
            color: #fff;
            border-radius: 0 0 0 3px;
            position: absolute;
            right: 0;
            top: 0;
          }
        }

        .modal{
          display: none;
          width: 100%;
          height: 115px;
          position: absolute;
          top:0;
          left: 0;
          background: rgba(0, 0, 0, .6);
          .icon {
            display: block;
            text-align: center;
            width: 100%;
            height: 50px;
            padding: 10px;
            color: #fff;

            &:hover{
              color: #598eea;
            }
          }
        }

        &:hover{
          .modal{
            display: block;
          }
        }
      }

      &::after {
        content: " ";
        display: table;
        height: 0;
        clear: both;
        visibility: hidden;
      }
    }

    :deep(.el-pagination) {
      padding: 5px;
      margin: 0 24px 0 20px;
      justify-content: flex-end;
      * {
        background: none;
      }
    }
  }
  .elx-upload-main {
    padding-left: 70px;
    .elx-upload-foot {
      padding: 15px 0 15px 10px;
      text-align: left;
      .el-button {
        margin: 0 0 0 10px;
      }
    }
  }

  div :deep(.el-tabs__header){
    display: none !important;
  }
}
</style>
